/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.manager.search;

import br.com.foxline.enums.CivilStatus;
import br.com.foxline.enums.Gender;
import br.com.foxline.enums.TypeAddress;
import br.com.foxline.model.Address;
import br.com.foxline.model.Annex;
import br.com.foxline.model.City;
import br.com.foxline.model.Customer;
import br.com.foxline.service.CityService;
import br.com.foxline.service.CustomerService;
import br.com.foxline.util.Caracter;
import br.com.foxline.util.Msg;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author ely
 */
@ManagedBean
@ViewScoped
public class ManagerSearchCustomer {

    @EJB
    CustomerService customerService;
    @EJB
    CityService cityService;
    private Customer customer;
    private Customer conjugue;
    private List<Customer> customers;
    private List<Annex> annexs;
    private Customer editCustomer;
    private String eCustomer;
    private Customer showCustomer;
    private String sCustomer;
    private City city;
    private Address address;
    private List<Address> addresses;
    private Annex annex;

    @PostConstruct
    public void init() {
        customer = new Customer();
        customers = new ArrayList<Customer>();

        conjugue = new Customer();

        address = new Address();
        annex = new Annex();

        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        eCustomer = params.get("eCustomer");
        sCustomer = params.get("sCustomer");
        paramPost();
    }

    public void addAddress() {
        address.setCity(city);
        address.setCep(Caracter.removecaracter(address.getCep()));
        addresses.add(address);
        address = new Address();
    }

    public void searchCustomer() {
        customer.setCpf(Caracter.removecaracter(customer.getCpf()));
        customers = customerService.findCustomer(customer);
    }

    public void paramPost() {
        try {
            if (sCustomer != null) {
                showCustomer = customerService.find(Long.parseLong(sCustomer));
                addresses = customerService.findAddresses(showCustomer);
                if (showCustomer.getSpouse() != null) {
                    conjugue = showCustomer.getSpouse();
                }
                annexs = customerService.findAnnex(showCustomer);

            } else if (eCustomer != null) {
                editCustomer = customerService.find(Long.parseLong(eCustomer));
                addresses = customerService.findAddresses(editCustomer);
                if (editCustomer.getSpouse() != null) {
                    conjugue = editCustomer.getSpouse();
                }
                annexs = customerService.findAnnex(editCustomer);

                System.err.println(editCustomer);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void ajaxTypeCivisStatus() {
        editCustomer.setCivilStatus(editCustomer.getCivilStatus());
        System.out.println(editCustomer);
    }

    public void update() {
        try {

            if (addresses.size() > 0) {
                if (typeCStatus()) {

                    if (conjugue.getId() == null) {
                        editCustomer.setCelPhone(Caracter.removecaracter(editCustomer.getCelPhone()));
                        editCustomer.setFixedPhone(Caracter.removecaracter(editCustomer.getFixedPhone()));
                        editCustomer.setCpf(Caracter.removecaracter(editCustomer.getCpf()));
                        conjugue.setCpf(Caracter.removecaracter(conjugue.getCpf()));
                        conjugue.setCelPhone(Caracter.removecaracter(conjugue.getCelPhone()));
                        conjugue.setFixedPhone(Caracter.removecaracter(conjugue.getFixedPhone()));
                        customerService.save(conjugue);
                        editCustomer.setSpouse(conjugue);
                        editCustomer.setAnnexs(annexs);
                        customerService.update(editCustomer);
                        Msg.messagemInfo("Cliente Atualizado com Sucesso");
                    } else {
                        editCustomer.setCelPhone(Caracter.removecaracter(editCustomer.getCelPhone()));
                        editCustomer.setFixedPhone(Caracter.removecaracter(editCustomer.getFixedPhone()));
                        editCustomer.setCpf(Caracter.removecaracter(editCustomer.getCpf()));
                        conjugue.setCpf(Caracter.removecaracter(conjugue.getCpf()));
                        conjugue.setCelPhone(Caracter.removecaracter(conjugue.getCelPhone()));
                        conjugue.setFixedPhone(Caracter.removecaracter(conjugue.getFixedPhone()));
                        editCustomer.setAnnexs(annexs);
                        editCustomer.setSpouse(conjugue);
                        customerService.update(editCustomer);

                        Msg.messagemInfo("Cliente Atualizado com Sucesso");
                    }
                } else {
                    editCustomer.setCelPhone(Caracter.removecaracter(editCustomer.getCelPhone()));
                    editCustomer.setFixedPhone(Caracter.removecaracter(editCustomer.getFixedPhone()));
                    editCustomer.setCpf(Caracter.removecaracter(editCustomer.getCpf()));
                    editCustomer.setAddresses(addresses);
                    editCustomer.setAnnexs(annexs);
                    customerService.update(editCustomer);
                    Msg.messagemInfo("Cliente Atualizado com Sucesso");

                }
            } else {
                Msg.messagemWarn("O Cliente deve possuir um endereço");
            }

        } catch (Exception e) {
            Msg.messagemError("Erro ao Salvar Cliente.");
        }
    }

    public boolean typeCStatus() {
        boolean b;
        if (editCustomer.getCivilStatus() == CivilStatus.CASADO) {
            b = true;
        } else {
            b = false;
        }
        return b;
    }

    public void customerExist() {

        conjugue.setCpf(Caracter.removecaracter(conjugue.getCpf()));
        Customer c = customerService.existCustomer(conjugue);
        if (c != null) {
            conjugue = customerService.find(c.getId());
            editCustomer.setSpouse(conjugue);
        } else {

            if (conjugue.getCpf() != null) {
                String cpf;
                cpf = conjugue.getCpf();
                conjugue = new Customer();
                conjugue.setCpf(cpf);
                conjugue.setCelPhone(Caracter.removecaracter(conjugue.getCelPhone()));
                System.out.println("Conjugue - " + conjugue);
            }
        }
    }

    public void edit(Address ad, int id) {
        System.out.println(ad);
        address = ad;
        city = cityService.find(address.getCity().getId());
        addresses.remove(id);

    }

    public void remove(int id) {
        addresses.remove(id);
    }

    public List<SelectItem> getGender() {
        List<SelectItem> genders = new ArrayList<SelectItem>();
        for (Gender ms : Gender.values()) {
            genders.add(new SelectItem(ms, ms.getName()));
        }
        return genders;
    }

    public List<SelectItem> getCivilStatus() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (CivilStatus c : CivilStatus.values()) {
            items.add(new SelectItem(c, c.getName()));
        }
        return items;
    }

    public List<SelectItem> getTypeAddress() {
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (TypeAddress c : TypeAddress.values()) {
            items.add(new SelectItem(c, c.getName()));
        }
        return items;
    }

    public void handle(FileUploadEvent event) throws IOException {
        handleAux(event.getFile().getContents(), event.getFile().getFileName(),
                event.getFile().getContentType(), event.getFile().getInputstream());
    }

    private void handleAux(byte[] imageBytes, String nome, String tipo, InputStream is) throws IOException {

        byte[] bytes = null;

        annex = new Annex();
        bytes = imageBytes;
        annex.setType(tipo);
        annex.setDescricao(nome);
        if (bytes != null) {
            annex.setFileByte(bytes);
            annexs.add(annex);
            annex = new Annex();
            Msg.messagemWarn("Anexado com Sucesso ");
        }

    }

    public List<City> autocompleteCity(String query) {
        return cityService.autocomplete(query);
    }

    public void cleanAddress() {
        this.address = new Address();
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public List<Customer> getCustomers() {
        return customers;
    }

    public void setCustomers(List<Customer> customers) {
        this.customers = customers;
    }

    public void clean() {
        this.customer = new Customer();
    }

    public Customer getEditCustomer() {
        return editCustomer;
    }

    public void setEditCustomer(Customer editCustomer) {
        this.editCustomer = editCustomer;
    }

    public Customer getShowCustomer() {
        return showCustomer;
    }

    public void setShowCustomer(Customer showCustomer) {
        this.showCustomer = showCustomer;
    }

    public List<Annex> getAnnexs() {
        return annexs;
    }

    public void setAnnexs(List<Annex> annexs) {
        this.annexs = annexs;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public City getCity() {
        return city;
    }

    public void setCity(City city) {
        this.city = city;
    }

    public List<Address> getAddresses() {
        return addresses;
    }

    public void setAddresses(List<Address> addresses) {
        this.addresses = addresses;
    }

    public Customer getConjugue() {
        return conjugue;
    }

    public void setConjugue(Customer conjugue) {
        this.conjugue = conjugue;
    }
}
